import java.util.*;

/**
 * @author LKQ
 * @date 2022/3/27 9:40
 * @description BFS
 */
public class Solution {
    public static void main(String[] args) {

    }
    public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) {
        if (n == 1) {
            return 0;
        }
        int length = manager.length;
        List<Integer>[] lists = new List[length];
        for (int i = 0; i < length; i++) {
            if (manager[i] == -1) {
                continue;
            }
            if (lists[manager[i]] == null) {
                lists[manager[i]] = new ArrayList<>();
            }
            lists[manager[i]].add(i);
        }
        int minute = 0;
        Queue<Integer> q = new ArrayDeque<>();
        q.add(headID);
        while (!q.isEmpty()) {
            int size  = q.size();
            while (size > 0) {
                int id = q.poll();
                if (lists[id] != null) {
                    for (int a: lists[id]) {
                        q.add(a);
                    }

                }
                size--;
                minute += informTime[id];
            }

        }
        return minute;
    }
}
